package ru.niir.goodfil.ui;

import org.apache.commons.lang.StringUtils;
import ru.niir.goodfil.db.StorageEnterance;
import ru.niir.goodfil.db.dic.OperationState;
import ru.niir.goodfil.ui.models.ReceiptAndDebitingModel;
import ru.niir.goodfil.utils.Pair;
import ru.niir.goodfil.utils.filters.StorageEnteranceFilter;

import javax.faces.model.SelectItem;
import java.util.*;

public class StorageReceiptAndDebitingBean extends PageBean{

    private String goodCode;

    private StorageEnteranceFilter filter;

    public StorageReceiptAndDebitingBean() {
        init();
    }

    public void init(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        StorageEnteranceFilter enteranceFilter = new StorageEnteranceFilter();
        enteranceFilter.setBeginDate(calendar.getTime());
        enteranceFilter.setEndDate(new Date());
        setFilter(enteranceFilter);
        setGoodCode("");
    }

    public List<ReceiptAndDebitingModel> getReceiptAndDebitingModels(){
        List<ReceiptAndDebitingModel> result = new ArrayList<ReceiptAndDebitingModel>();
        List<StorageEnterance> enterances = gf().getStorageEnteraces(getFilter());
        for(StorageEnterance enterance : enterances){
            ReceiptAndDebitingModel model = new ReceiptAndDebitingModel();
            model.setGoodCount(enterance.getGoodCount());
            model.setGoodCode(gf().getGoodById(enterance.getGoodId()).getCode());
            model.setOperationType(OperationState.asString(enterance.getOperationType()));
            model.setUserName(gf().getUserById(enterance.getUserId()).getFio());
            model.setComment(enterance.getComment());
            model.setDate(enterance.getDate());
            result.add(model);
        }
        return result;
    }

    public List<SelectItem> getOperationTypes(){
        List<SelectItem> list = new ArrayList<SelectItem>();
        list.add(new SelectItem(-1, "Не выбрано"));
        for(Pair pair : OperationState.list()){
            list.add(new SelectItem(pair.getId(), pair.getValue()));
        }
        return list;
    }

    public void applyFilter(){
        if(!StringUtils.isBlank(getGoodCode())){
            getFilter().setGoodId(gf().getGoodByCode(getGoodCode()).getId());
        }
    }

    public String getGoodCode() {
        return goodCode;
    }

    public void setGoodCode(String goodCode) {
        this.goodCode = goodCode;
    }

    public StorageEnteranceFilter getFilter() {
        return filter;
    }

    public void setFilter(StorageEnteranceFilter filter) {
        this.filter = filter;
    }

}
